package com.mybed.crm.aop;

import com.alibaba.fastjson.JSON;
import com.mybed.crm.anno.Log;
import com.mybed.crm.mapper.OperationMapper;
import com.mybed.crm.mapper.UserMapper;
import com.mybed.crm.pojo.pojo.Operation;
import com.mybed.crm.pojo.pojo.User;
import com.mybed.crm.utils.thread.UserThreadLocalUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

@Aspect
@Component
@Slf4j
public class OperateLogAspect {
    @Autowired
    HttpServletRequest httpServletRequest;
    @Autowired
    private OperationMapper logMapper;
    @Autowired
    private UserMapper userMapper;
    @Around("execution(* com.mybed.crm.controller.*.*(..)) && @annotation(com.mybed.crm.anno.Log)")
    public Object recodeLog(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取当前操作人的id (登录员工的id)
        String userId = UserThreadLocalUtil.getUser();
        User user = userMapper.selectById(userId);
        //logValue
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Log log = signature.getMethod().getAnnotation(Log.class);
        String value = log.value();
        // 获取操作类名
        String className = joinPoint.getTarget().getClass().getName();
        // 获取执行方法名
        String methodName = joinPoint.getSignature().getName();
        //请求的Url名字
        String method = httpServletRequest.getMethod();
        //获取执行请求的类型
        String uri = httpServletRequest.getRequestURI();
        // 方法运行时参数
        Object[] args = joinPoint.getArgs();
        List<Object> list = Arrays.asList(args);
        // 方法的返回值
        Object result = joinPoint.proceed();
        Operation operation=Operation.builder()
                .title(value)
                .businessType(2)
                .method(className+methodName)
                .requestMethod(method)
                .operatorType(1)
                .operName(user.getUserName())
                .operUrl(uri)
                .operIp(user.getLoginIp())
                .operLocation("XX.XX")
                .operParam(JSON.toJSONString(list))
                .jsonResult(JSON.toJSONString(result))
                .status(0)
                .operTime(LocalDateTime.now())
                .build();
        logMapper.insert(operation);
        return result;

    }

}
